package com.lpf.nashorn;

import org.junit.Before;
import org.junit.Test;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.net.URL;

public class TestNashorn_extend {

    private String filePath;

    @Before
    public void findFile() {
        URL resource = TestNashorn_extend.class.getClassLoader().getResource("script_extend.js");
        filePath = resource.getPath();
    }

    @Test
    public void test_fun_array() throws Exception {
        execute("fun_array");
    }

    @Test
    public void test_fun_collection() throws Exception {
        execute("fun_collection");
    }

    @Test
    public void test_fun_foreach() throws Exception {
        execute("fun_foreach");
    }

    @Test
    public void test_fun_lambda_streams() throws Exception {
        execute("fun_lambda_streams");
    }

    @Test
    public void test_fun_type_extend() throws Exception {
        execute("fun_type_extend");
    }

    @Test
    public void test_fun_param_override() throws Exception {
        execute("fun_param_override");
    }

    @Test
    public void test_fun_binding() throws Exception {
        execute("fun_binding");
    }

    @Test
    public void test_fun_where() throws Exception {
        execute("fun_where");
    }

    @Test
    public void test_fun_import() throws Exception {
        execute("fun_import");
    }

    @Test
    public void test_fun_array_convert() throws Exception {
        execute("fun_array_convert");
    }

    @Test
    public void test_fun_super_method() throws Exception {
        execute("fun_super_method");
    }

    @Test
    public void test_fun_remote_js() throws Exception {
        execute("fun_remote_js");
    }

    private void execute(String jsName) throws ScriptException, FileNotFoundException, NoSuchMethodException {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
        engine.eval(new FileReader(filePath));
        Invocable invocable = (Invocable) engine;
        invocable.invokeFunction(jsName);
    }

}
